package com.hoshiicloud.goods.service.impl;


import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hoshiicloud.common.aop.Logable;
import com.hoshiicloud.common.exception.CommonError;
import com.hoshiicloud.common.exception.ServiceException;
import com.hoshiicloud.common.query.OmnipotentParam;
import com.hoshiicloud.common.query.OmnipotentWrapper;
import com.hoshiicloud.common.update.UpdateBatchParam;
import com.hoshiicloud.goods.entity.spu.BaseSpu;
import com.hoshiicloud.goods.feign.IdGeneratorService;
import com.hoshiicloud.goods.mapper.spu.BaseSpuMapper;
import com.hoshiicloud.goods.service.BaseSkuService;
import com.hoshiicloud.goods.service.BaseSpuService;
import com.hoshiicloud.goods.service.ExtSkuService;
import com.hoshiicloud.goods.service.ExtSpuService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.List;

/**
 * <p>
 * 商品表 服务实现类
 * </p>
 *
 * @author zhangshuhu
 * @since 2019-06-04
 */
@Slf4j
@Service
public class BaseSpuServiceImpl extends ServiceImpl<BaseSpuMapper, BaseSpu> implements BaseSpuService {

    @Autowired
    private IdGeneratorService idGeneratorService;
    @Autowired
    private BaseSpuMapper baseSpuMapper;
    @Autowired
    private BaseSkuService baseSkuService;
    @Autowired
    private ExtSpuService extSpuService;
    @Autowired
    private ExtSkuService extSkuService;
    /**
     * @param id
     * @return BaseSpu
     * @description: 根据id查询商品表
     */
    @Override
    @Cacheable(cacheNames = "BaseSpu", key = "#root.targetClass.simpleName+':'+#root.methodName+':'+#id")
    @Logable(authName = "商品管理-商品表-查询商品表 ")
    public BaseSpu getById(Long id) {
        return baseMapper.selectById(id);
    }


    /**
     * @param entity
     * @return boolean
     * @description: 新增商品表
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    @CacheEvict(cacheNames = "BaseSpu", allEntries = true)
    @Logable(authName = "商品管理-商品表-新增商品表")
    public boolean save(BaseSpu entity) {

        // 生成主键
        String id = idGeneratorService.queryGeneratorId();
        if (StringUtils.isBlank(id)) {
            throw new ServiceException(CommonError.error("新增失败"));
        }

        // 添加数据
        entity.setId(Long.parseLong(id));
        entity.setCreatedTime(LocalDateTime.now());

        int row = baseMapper.insert(entity);
        if (row <= 0) {
            throw new ServiceException(CommonError.error("新增失败"));
        }
        return true;
    }

    /**
     * @param entity
     * @return boolean
     * @description: 修改商品表
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    @CacheEvict(cacheNames = "BaseSpu", allEntries = true)
    @Logable(authName = "商品管理-商品表管理-修改商品表")
    public boolean updateById(BaseSpu entity) {

        // 更新数据
        entity.setUpdatedTime(LocalDateTime.now());
        int row = baseMapper.updateById(entity);
        if (row <= 0) {
            throw new ServiceException(CommonError.error("修改失败"));
        }
        return true;
    }

    /**
     * @param queryWrapper 查询条件
     * @return IPage
     * @description: 分页查询商品表
     */
    @Override
    @Logable(authName = "商品管理-商品表管理-分页查询商品表")
    @Cacheable(cacheNames = "BaseSpu", key = "T(com.hoshiicloud.common.utils.DigestUtils).md5(#root.targetClass.simpleName+':'+#root.methodName+':'+#key)")
    public Page getPage(IPage page, Wrapper queryWrapper, String key) {
        return (Page) baseMapper.selectPage(page, queryWrapper);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    @CacheEvict(cacheNames = "BaseSpu", allEntries = true)
    @Logable(authName = "商品管理-商品表管理-删除商品表")
    public boolean deleteById(Long id) {

        // 根据id查询该数据是否存在
        BaseSpu entity = this.getById(id);
        if (entity == null) {
            throw new ServiceException("删除商品表异常，无法找到商品表记录");
        }

        //进行删除操作
        entity.setUpdatedTime(LocalDateTime.now());
        entity.setDeleted(1);
        int row = baseMapper.updateById(entity);
        if (row <= 0) {
            throw new ServiceException(CommonError.error("删除失败"));
        }
        return true;
    }

    @Override
    @Cacheable(cacheNames = "BaseSpu", key = "#root.targetClass.simpleName+':'+#root.methodName+':'+#key")
    @Logable(authName = "商品管理-商品表管理-根据id集合查询商品表")
    public List<BaseSpu> getByIds(List<Long> ids, String key) {
        return baseMapper.selectBatchIds(ids);
    }

    /**
     * 多条件批量查询
     */
    @Override
    public List<BaseSpu> listBaseSpu(BaseSpu baseSpu) {
        try {
            QueryWrapper<BaseSpu> queryWrapper = new QueryWrapper<BaseSpu>();
            queryWrapper.lambda().eq(baseSpu.getCompanyId() != null, BaseSpu::getCompanyId, baseSpu.getCompanyId())
                    .eq(baseSpu.getPlatformId() != null, BaseSpu::getPlatformId, baseSpu.getPlatformId())
                    .eq(baseSpu.getStoreId() != null, BaseSpu::getStoreId, baseSpu.getStoreId())
                    .eq(StringUtils.isNotBlank(baseSpu.getSpuNo()), BaseSpu::getSpuNo, baseSpu.getSpuNo())
                    .eq(StringUtils.isNotBlank(baseSpu.getTitle()), BaseSpu::getTitle, baseSpu.getTitle())
                    .eq(StringUtils.isNotBlank(baseSpu.getSubTitle()), BaseSpu::getSubTitle, baseSpu.getSubTitle())
                    .eq(baseSpu.getCategoryId() != null, BaseSpu::getCategoryId, baseSpu.getCategoryId())
                    .eq(baseSpu.getBrandId() != null, BaseSpu::getBrandId, baseSpu.getBrandId())
                    .eq(StringUtils.isNotBlank(baseSpu.getSaleUnit()), BaseSpu::getSaleUnit, baseSpu.getSaleUnit())
                    .eq(StringUtils.isNotBlank(baseSpu.getPacketUnit()), BaseSpu::getPacketUnit, baseSpu.getPacketUnit())
                    .eq(baseSpu.getWeight() != null, BaseSpu::getWeight, baseSpu.getWeight())
                    .eq(baseSpu.getTaxRate() != null, BaseSpu::getTaxRate, baseSpu.getTaxRate())
                    .eq(baseSpu.getGoodsLen() != null, BaseSpu::getGoodsLen, baseSpu.getGoodsLen())
                    .eq(baseSpu.getGoodsWidth() != null, BaseSpu::getGoodsWidth, baseSpu.getGoodsWidth())
                    .eq(baseSpu.getGoodsHeight() != null, BaseSpu::getGoodsHeight, baseSpu.getGoodsHeight())
                    .eq(baseSpu.getInnerBoxs() != null, BaseSpu::getInnerBoxs, baseSpu.getInnerBoxs())
                    .eq(baseSpu.getOuterBoxs() != null, BaseSpu::getOuterBoxs, baseSpu.getOuterBoxs())
                    .eq(StringUtils.isNotBlank(baseSpu.getPoAddress()), BaseSpu::getPoAddress, baseSpu.getPoAddress())
                    .eq(baseSpu.getSource() != null, BaseSpu::getSource, baseSpu.getSource())
                    .eq(StringUtils.isNotBlank(baseSpu.getExtendProperty()), BaseSpu::getExtendProperty, baseSpu.getExtendProperty())
                    .eq(StringUtils.isNotBlank(baseSpu.getExtendSpec()), BaseSpu::getExtendSpec, baseSpu.getExtendSpec())
                    .eq(baseSpu.getStatus() != null, BaseSpu::getStatus, baseSpu.getStatus())
                    .eq(baseSpu.getPublished() != null, BaseSpu::getPublished, baseSpu.getPublished())
                    .eq(baseSpu.getDeleted() != null, BaseSpu::getDeleted, baseSpu.getDeleted());
            return baseMapper.selectList(queryWrapper);
        }catch (Exception e) {
            throw new ServiceException("BaseSpu信息查询失败");
        }
    }

    @CacheEvict(cacheNames = "BaseSpu", allEntries = true)
    @Logable(authName = "保存baseSpu返回数据")
    @Override
    public BaseSpu saveBaseSpu(BaseSpu entity) {
        // 生成主键
        String id = idGeneratorService.queryGeneratorId();
        if (StringUtils.isBlank(id)) {
            throw new ServiceException(CommonError.error("新增失败"));
        }

        // 添加数据
        entity.setId(Long.parseLong(id));
        entity.setCreatedTime(LocalDateTime.now());

        int row = baseMapper.insert(entity);
        if (row <= 0) {
            throw new ServiceException(CommonError.error("新增失败"));
        }
        return entity;
    }

    @CacheEvict(cacheNames = "BaseSpu", allEntries = true)
    @Logable(authName = "根据自定义条件批量更新")
    @Override
    public Boolean updateBatchByWrapper(UpdateBatchParam<BaseSpu> updateBatchParam) {
        BaseSpu updateEntity = updateBatchParam.getUpdateEntity();
        QueryWrapper<BaseSpu> wrapper = updateBatchParam.getWrapper();
        return this.update(updateEntity, wrapper);
    }

    @CacheEvict(cacheNames = "BaseSpu", allEntries = true)
    @Logable(authName = "批量更新")
    @Override
    public Boolean updateBatch(OmnipotentParam<BaseSpu> param) {
        OmnipotentWrapper<BaseSpu> wrapper = new OmnipotentWrapper<>();
        UpdateWrapper<BaseSpu> updateWrapper = wrapper.getUpdateWrapper(param.getWrappers());
        BaseSpu entity = param.getEntity();
        return this.update(entity, updateWrapper);
    }
}
